#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    int pipe_fd[2];
    pid_t  pid;
    char buf_r[100];
    char *p_wbuf;
    int r_num;
    memset(buf_r, 0, sizeof(buf_r));
    //creating a pipe in parent process
    if(pipe(pipe_fd) < 0)
    {
        printf("pipe create error\n"); 
        return -1;
    }
    //creating a subprocess
    if((pid = fork()) == 0)
    {
        printf("\n"); 
        //closing the writing descriptor of subprocess,and suspending the parent process for 2 seconds to ensure that parent process had closed corresponding reading descriptor
        close(pipe_fd[1]);
        sleep(2);
        //subprocess reads the content of pipe
        if((r_num = read(pipe_fd[0], buf_r, 100)) > 0)
        {
            printf("%d numbers read from pipe is %s\n", r_num, buf_r); 
        }
        //closing the reading descriptor of subprocess
        close(pipe_fd[0]);
        exit(0);
    }
    else if(pid > 0)
    {
        //closing the reading descriptor of parent process, and write "Hello pipe" to the pipe by twice
        close(pipe_fd[0]);
        if(write(pipe_fd[1], "Hello", 5) != -1)
          printf("parent write1 success!\n");
        if(write(pipe_fd[1], " pipe", 5) != -1)
          printf("parent write2 success!\n");

        //closig the descriptor of parent process
        close(pipe_fd[1]);
        sleep(3);
        //collecting the exit infomation of subprocess
        waitpid(pid,NULL,0);
        exit(0);
    }
}
